<script setup>
import QRCode from 'qrcode';
import { ref, nextTick, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {listMemberTypeInfo, createOrder, loginApi, cancelOrder, pay, findPayState, getUserInfo, register,send} from '@/api';
import { ArrowDown } from '@element-plus/icons-vue'
const vipData = ref([])
const qrCode = ref(null)
const Userform = ref(null)
const cardActive = ref(0)
const isActivate = ref(false)
const orderForm = ref(false)
const loadingActive = ref(false)
const login = ref(false)
const codeNumber = ref(0)
const interval = ref(0)
const userInfo = ref(null)
const TransactionOrder = ref('')
const QueryOrderStatusTimedtasks = ref(0)
const loginUser = ref({
  phone: '',
  password: '',
  code: '',
})
// 0-注册  1-登录  2-修改密码
const loginActive = ref(0)
watch(loginActive, (value) => {
  Userform.value.resetFields()
})



//接口钩子
onMounted(() => {
  //初始化数据
  initData()
})


const initData = async () => {
  userInfo.value = JSON.parse(localStorage.getItem("userInfo"))
  console.log(userInfo.value)
  //初始化数据在这写
  const { data } = await listMemberTypeInfo()
  vipData.value = data
  vipData.value.push({
    memberType: '免费版',
    validity: 0,
    favorablePrice: 0,
    price: 0
  })
  console.log(data)
  // if (code == 200) {
  //   console.log(data)
  // } else {
  //   console.log('获取会员类型失败')
  // }


}

const getCode = () => {
  console.log('发送验证码')
  if (interval.value) {
    return
  }
  sendCode();
  codeNumber.value = 59
  interval.value = setInterval(() => {
    if (codeNumber.value-- <= 0) {
      clearInterval(interval.value)
      interval.value = 0
    }
  }, 1000)
}
// 手机号校验
const validatePhone = (rule, value, callback) => {
  if (value === '' || !/^1[3-9]\d{9}$/.test(value)) {
    ElMessage.error('手机号格式不正确')
    callback(new Error(''))
  } else {
    callback()
  }
}
// 密码校验
const validatePassword = (rule, value, callback) => {
  if (value === '' || !/^.{6,30}$/.test(value)) {
    ElMessage.error('请输入6-30位密码')
    callback(new Error(''))
  } else {
    callback()
  }
}
//验证码校验
const validateCode = (rule, value, callback) => {
  if (value === '' && (loginActive === 0 || loginActive === 2)) {
    ElMessage.error('验证码错误')
    callback(new Error(''))
  } else {
    callback()
  }
}
//配置校验
const rules = ref({
  phone: [{ validator: validatePhone, trigger: 'submit' }],
  password: [{ validator: validatePassword, trigger: 'submit' }],
  code: [{ validator: validateCode, trigger: 'submit' }],
})
// 表单提交
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //通过校验
      switch (loginActive.value) {
        case 1: Gologin(); break;
        case 0: Register(); break;
      }



      // loadingActive.value = true;
      // setTimeout(() => {
      //   loadingActive.value = false;
      // }, 2000)


    }
  })
}

//登录接口
const Gologin = async () => {
  try {
    const { code, data, msg } = await loginApi(loginUser.value)
    if (code != 200) {
      ElMessage.error(msg)
      return
    } else {
      ElMessage.success('登录成功')
      localStorage.setItem('userInfo', JSON.stringify(data))
      userInfo.value = data
      login.value = false
      isActivate.value = false
    }

    alert(res)
  } catch (e) {


    return
  }
}


//注册接口
const Register = async () => {
  try {
    const { code, data, msg } = await register(loginUser.value)
    if (code != 200) {
      ElMessage.error(msg)
      return
    } else {
      ElMessage.success('注册成功')
      login.value = false
      isActivate.value = false
      loginUser.value = ref({
        phone: '',
        password: '',
        code: '',
      })
    }

    alert(res)
  } catch (e) {


    return
  }
}

//发送验证码
const sendCode = async () => {
  try {
    const { code, msg } = await send(loginUser.value)
    if (code != 200) {
      ElMessage.error(msg)
      return
    } else {
      return
    }

    alert(res)
  } catch (e) {


    return
  }
}
//点击立即开通
const openActivate = (item) => {
  if (item.memberType === '免费版') return
  if (!userInfo.value?.userId) {
    ElMessage.warning('请先登录')
    return
  }
  isActivate.value = true
}
//打开支付订单
const openOrderForm = async () => {
  //创建订单
  if (userInfo.value == null || !userInfo.value.userId) {
    ElMessage.success('请先登录!')
    // loginActive.value = 1
    login.value = true
    return
  }
  orderForm.value = true
  isActivate.value = false
  const option = {
    memberId: vipData.value[cardActive.value].memberId,
    userId: userInfo.value.userId,
    payment: 1
  }
  try {
    const { code, data: { orderNo } } = await createOrder(option)
    if (code == 200) {
      TransactionOrder.value = orderNo
      //创建订单成功
      const formData = new FormData();
      formData.append('orderNo', orderNo)
      const { code, data } = await pay(formData)
      if (code == 200) {
        //获取二维码成功
        generateQRCode(data)

      } else {
        ElMessage.success('订单创建失败!')
      }

    }
  } catch (e) {
    console.error(e)
  }


}

//编写二维码
const generateQRCode = async (text) => {
  const options = {
    width: 200,
    height: 200,
  };
  await nextTick()
  QRCode.toCanvas(qrCode.value, text, options, (error, canvas) => {
    if (error) {
      console.error(error);
      return
    }
    //创建定时任务查询订单支付进度
    QueryOrderStatus()
  });
}
//创建定时任务查询订单支付进度
const QueryOrderStatus = () => {
  const formData = new FormData();
  formData.append('orderId', TransactionOrder.value)
  let i = true
  QueryOrderStatusTimedtasks.value = setInterval(async () => {
    const { code, data: { orderState } } = await findPayState(formData)

    if (code == 200) {

      !orderState && ElMessage.warning('订单已过期');
      orderState === -1 && ElMessage.success('订单已取消');
      if (orderState === 2) {
        ElMessage.success('支付成功!');
        orderForm.value = false
        const userFormData = new FormData();
        userFormData.append('userId', userInfo.value.userId)
        const { code, data } = await getUserInfo(userFormData)

        if (code == 200) {
          userInfo.value = data
          localStorage.setItem('userInfo', data)
        }
      }
      if (orderState !== 1) clearInterval(QueryOrderStatusTimedtasks.value);
    }
  }, 1000)


}
//关闭支付弹窗
const orderDialogClose = async () => {
  // try {
  //   await cancelOrder({ orderNo: TransactionOrder.value })
  // } catch (error) {
  //   console.log("接口异常:", error)
  // }

}
const protocol = () => {
  if (loginActive.value === 2) {
    //修改密码跳转登录
    loginActive.value = 1

  }

}


//退出登录
const outLogin = () => {
  localStorage.removeItem('userInfo')
  ElMessage.success('退出成功')
  userInfo.value = false
}
</script>

<template>
  <div class="payment">
    <el-row tag="header" justify="center">
      <el-col :span="7">
        <div class="header-title">
          <div></div>
          <div>AI会员支付平台</div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="header-tabs">
          <div class="active">首页</div>
          <div>付费订阅</div>
        </div>
      </el-col>
      <el-col :span="7" class="header-login">
        <el-button v-if="!userInfo" @click="login = true" type="primary" size="small">登录注册</el-button>
        <!-- <div class="userInfo" v-else><span>{{ userInfo?.nickName }}</span></div> -->

        <el-dropdown v-else>
          <span class="userInfo">
            {{ userInfo?.nickName }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>用户名: {{ userInfo.userName }}({{ userInfo.memberType }})</el-dropdown-item>
              <el-dropdown-item>邮箱: {{ userInfo.email }}</el-dropdown-item>
              <el-dropdown-item>到期时间: {{ userInfo.memberExpirationDate }}</el-dropdown-item>
              <el-dropdown-item @click="outLogin" divided>退出登录 </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>

    </el-row>
    <div class="payment-title">
      <h1><span>AI</span><span>产品标题</span></h1>
      <p>输入你的内容主题，让A1为你一站式服务到底</p>
    </div>
    <div class="payment-card">
      <el-card @click="cardActive = index" :class="`card-item ${cardActive === index ? 'active' : ''}`"
        v-for="item, index in vipData" :key="item.memberId">
        <span class="taps" v-if="item.memberType != '免费版'">限时折扣</span>
        <div class="vip-type">
          <div v-if="item.memberType != '免费版'" class="card-item-crown"></div>
          <div v-else></div>

          <div>{{ item.memberType }}</div>
        </div>
        <div class="vip-time">{{ item.memberType != '免费版' ? Math.floor(item.validity / 30) + "个月" : '普通用户' }} </div>
        <div class="vip-price" v-if="item.memberType != '免费版'">
          <div class="priceI"><span>¥</span><span>{{ item.favorablePrice/100 }}</span></div>
          <div class="priceS"> <span>¥</span><span>{{ item.price/100 }}</span></div>
        </div>
        <div class="vip-price" style="height: 94px;display: flex;align-items: center;" v-else>
          <div class="priceI"><span></span><span style="color: black;font-size: 36px;">免费</span></div>
        </div>
        <div @click="openActivate(item)" class="vip-activate">
          <div>立即开通</div>
        </div>
        <hr style="opacity: 0.2;">
        <div class="vip-describe">
          <div class="describe-item" v-for="ite in 4"><span>描述1</span><span class="icon-Checkmark"></span>
          </div>
        </div>
      </el-card>

    </div>
    <!-- 支付提示弹窗 -->
    <el-dialog v-model="isActivate" title="支付提示" width="440" height="179" align-center>
      <div style="margin-bottom: 50px;"><span>我同意并接受 《<a
            style="color:var(--el-color-primary);cursor: pointer;">个人订阅服务协议</a>》</span></div>
      <el-button @click="openOrderForm" style="float: right;" size="small" type="primary">同意支付</el-button>
    </el-dialog>
    <!-- 交易订单二维码弹窗 -->
    <el-dialog class="orderForm" :show-close="false" v-model="orderForm" width="800" align-center
      @close="orderDialogClose">
      <div class="orderForm-header">
        <span>交易订单: {{ TransactionOrder }}</span>
        <span>购买物品:<span style="color: var(--el-color-primary);"> {{ vipData[cardActive].memberType }}</span></span>
      </div>
      <hr style="opacity: 0.2;margin: 20px 0;">
      <div class="orderForm-price">
        <div>支付金额: </div>
        <div><span>¥</span><span>{{ vipData[cardActive].favorablePrice/100 }}</span></div>
      </div>
      <div class="orderForm-qrCode">
        <span>微信支付</span>
        <span>扫描下方二维码完成支付</span>
        <div>
          <canvas ref="qrCode"></canvas>
          <span></span>
        </div>
      </div>
    </el-dialog>
    <!-- 登录 -->
    <el-dialog class="login" v-model="login" title="Tips" width="500" align-center>
      <template #header="{ close, titleId, titleClass }">
        <div class="login-header">
          <div></div>
          <div>产品标题</div>
        </div>
      </template>
      <div class="login-main">
        <div class="title">
          <template v-if="loginActive !== 2">
            <span :style="`${loginActive === 0 && 'color: black;'}`" @click="loginActive = 0">注册</span>
            <span> –</span>
            <span :style="`${loginActive === 1 && 'color: black;'}`" @click="loginActive = 1">登录</span></template>
          <span style="color: black;" v-else>修改密码</span>
        </div>
        <el-form class="login-form" :model="loginUser" :rules="rules" label-width="auto" ref="Userform"
          style="width: 280px">
          <el-form-item prop="phone">
            <el-input v-model="loginUser.phone" placeholder="手机号" maxlength="20">
              <template #prefix>
                <div class="icon-phone"></div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginUser.password" maxlength="20"
              :placeholder="`填写${loginActive === 0 || loginActive === 2 ? '6 - 30位' : ''}密码`">
              <template #prefix>
                <div class="icon-password"></div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="height: 32px;" prop="code">
            <div v-if="loginActive === 0 || loginActive === 2" class="login-Verification">
              <el-input v-model="loginUser.code" placeholder="验证码" maxlength="10" style="width: 170px;" />
              <el-button @click="getCode" style="width: 100px;"><span v-if="codeNumber > 0" style="color: #c3c4c9;">{{
                codeNumber
              }}秒后获取</span><span v-else>获取验证码</span>
              </el-button>
            </div>
            <div v-else class="login-modify" @click="loginActive = 2">忘记密码</div>
          </el-form-item>
          <el-form-item>
            <el-button @click="submitForm(Userform)" :class="`login-submit ${loadingActive ? 'loading-active' : ''}`"
              type="primary">

              <div v-if="loadingActive" class="loading"></div>
              {{ loginActive === 0 ? '注册' : loginActive === 1 ? '登录' : '确认修改' }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <div class="login-protocol"><span>{{ loginActive === 0 || loginActive === 1 ? '我已阅读并同意' : '想起密码?' }}
              </span><span @click="protocol">{{ loginActive === 0 || loginActive === 1 ? '服务协议、隐私协议' : '去登录?' }}</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.payment {
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, #DCE3FF 0.23%, #F5F7FF 22.96%, #FFF 40.16%, #FFF 100%);
  padding-top: 10px;

  header {

    .header-title {
      display: flex;
      justify-content: center;
      align-items: center;

      div:nth-child(1) {
        width: 18px;
        height: 18px;
        background-color: #a4a4a7;
        margin-right: 3px;
      }

      div:nth-child(2) {
        font-size: 14px;
        font-weight: 600;
      }
    }

    .header-tabs {
      display: flex;
      justify-content: center;
      align-items: center;

      div {
        margin-right: 10px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
      }

      .active {
        color: var(--el-color-primary)
      }
    }

    .header-login {
      display: flex;
      justify-content: center;
      align-items: center;

      .userInfo {
        cursor: pointer;

        display: flex;
        align-items: center;

        &:hover {
          border: none !important;
        }

        .el-dropdown-link {
          cursor: pointer;
          color: var(--el-color-primary);
          display: flex;
          align-items: center;
        }

      }
    }
  }

  .payment-title {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 80px 0;
    flex-direction: column;

    h1 {
      font-family: "Microsoft YaHei UI";
      font-size: 60px;
      font-style: normal;
      font-weight: 600;
      line-height: normal;

      span:nth-child(1) {
        color: var(--el-color-primary);
        margin-right: 6px;

      }

      margin-bottom: 10px;
    }

    p {
      color: #666;
      text-align: center;
      font-family: "Microsoft YaHei UI";
      font-size: 18px;
      font-style: normal;
      font-weight: 400;
      line-height: 30.6px;
      /* 170% */
    }
  }


  .payment-card {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;

    .card-item {
      height: 500px;
      width: 280px;
      margin: 0 10px;
      position: relative;
      border-radius: 8px;
      padding-top: 15px;

      .taps {
        position: absolute;
        right: 0;
        top: 0;
        height: 32px;
        width: 80px;
        font-size: 14px;
        border-radius: 0px 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #FFF;
        background: linear-gradient(90deg, #FE7E48 0%, #FF404A 100%), linear-gradient(90deg, #1581FF 0%, #1665FF 51%, #175AFE 100%);
      }

      .vip-type {
        display: flex;
        align-items: center;
        margin: 10px 0;

        .card-item-crown {
          margin-right: 2px;
          width: 24px;
          height: 24px;
          background: url('@/assets/image/crown.svg') no-repeat center;
        }

        div:nth-child(2) {
          color: #090B10;
          font-family: "Microsoft YaHei UI";
          font-size: 20px;
          font-style: normal;
          font-weight: 600;
          line-height: normal;
        }
      }

      .vip-time {
        color: #666;
        font-family: "Microsoft YaHei UI";
        font-size: 14px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;
      }

      .vip-price {
        margin: 15px 0;

        div {
          span:nth-child(1) {
            font-size: 20px;
            font-style: normal;
            font-weight: 700;
            line-height: normal;
          }
        }

        .priceI {
          span {
            color: #FF404A;
          }

          span:nth-child(2) {
            color: #FF083D;
            font-size: 48px;
            font-style: normal;
            font-weight: 600;
            line-height: normal;
          }
        }

        .priceS {
          color: #55698D;

          span:nth-child(2) {
            font-family: D-DIN-PRO;
            font-size: 20px;
            font-style: normal;
            font-weight: 700;
            line-height: normal;
            text-decoration: line-through;
          }

        }
      }

      .vip-activate {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 25px 0;

        div {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 224px;
          height: 44px;
          padding: 10px;
          gap: 10px;
          flex-shrink: 0;
          cursor: pointer;
          border-radius: 6px;
          color: var(--el-color-primary);
          background: #ECF0FF;
        }


      }

      .vip-describe {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 20px 0;

        .describe-item {
          height: 25px;
          width: 100%;
          display: flex;
          justify-content: space-between;
          margin: 6px 0;

          .icon-Checkmark {
            width: 16px;
            height: 16px;
            background: url('@/assets/image/Checkmark.svg') no-repeat center;
          }
        }
      }
    }

    .active {
      border: 3px solid #D357FF;
      border-radius: 15px;

      .vip-activate {
        div {
          color: #ffffff;
          background: linear-gradient(90deg, #2855FF 0%, #D357FF 100%);
        }
      }
    }
  }

  .orderForm {


    .orderForm-header {
      display: flex;
      justify-content: center;
      align-items: start;
      color: #666;
      font-size: 14px;
      font-style: normal;
      font-weight: 600;
      line-height: normal;

      span {
        margin-right: 30px;
      }
    }

    .orderForm-price {
      display: flex;
      justify-content: center;
      align-items: center;

      div:nth-child(1) {

        color: #666;
        text-align: center;
        font-family: "Microsoft YaHei UI";
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
        margin-right: 20px;
      }

      div:nth-child(2) {
        color: #FC9311;
        font-family: D-DIN-PRO;
        font-size: 32px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;

        span:nth-child(1) {
          font-size: 20px;
        }
      }

    }

    .orderForm-qrCode {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      height: 350px;

      span:nth-child(1) {
        color: #000;
        text-align: center;
        font-family: "Microsoft YaHei UI";
        font-size: 20px;
        font-style: normal;
        font-weight: 900;
        line-height: normal;
        margin-bottom: 10px;
      }

      span:nth-child(2) {
        color: #666;
        text-align: center;
        font-family: "Microsoft YaHei UI";
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }

      div {
        position: relative;

        span {
          position: absolute;
          width: 32px;
          height: 32px;
          left: 0;
          top: 0;
          bottom: 0;
          right: 0;
          margin: auto;
          background: url('@/assets/image/weixin.svg') no-repeat center;
        }
      }

    }

  }

}

:deep(.orderForm>.el-dialog__header) {
  display: none !important;
}

:deep(.login) {
  background: linear-gradient(90deg, #EEF2FF 0%, #DFE7FF 100%) !important;
  width: 472px;
  height: 452px;
  padding: 0;
  border-radius: 12px;

  .login-header {
    width: 100%;
    position: absolute;
    left: 0;
    width: 472px;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;


    div:nth-child(1) {
      width: 32px;
      height: 32px;
      background-color: #a4a4a7;
      border-radius: 6px;
      margin-right: 8px;
    }

    div:nth-child(2) {
      color: #000;
      font-family: "Microsoft YaHei UI";
      font-size: 20px;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
    }

  }

  .login-main {
    background-color: #fff;
    height: 100%;
    height: 472px;
    margin-top: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .title {
      color: #666;
      font-size: 24px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;

      span:nth-child(2n-1) {
        cursor: pointer;
      }

      span:nth-child(2) {
        display: inline-block;
        transform: rotate(90deg);
        margin: 0 20px;
        opacity: 0.3;

      }
    }

    .login-form {
      margin: 30px 0;

      .login-modify {
        position: absolute;
        top: -6px;
        color: var(--el-color-primary);
        width: 100%;
        text-align: end;
        font-family: "Microsoft YaHei UI";
        font-size: 12px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;
        cursor: pointer;
      }

      .login-submit {
        width: 100%;
      }


      .login-protocol {
        span:nth-child(2) {
          color: var(--el-color-primary);
          text-align: center;
          font-family: "Microsoft YaHei UI";
          font-size: 12px;
          font-style: normal;
          font-weight: 600;
          line-height: normal;
          cursor: pointer;

        }
      }

      .login-Verification {
        position: absolute;
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

    }

  }

  .icon-phone {
    width: 16px;
    height: 16px;
    background: url('@/assets/image/phone.svg') no-repeat center;
  }

  .icon-password {
    width: 16px;
    height: 16px;
    background: url('@/assets/image/password.svg') no-repeat center;
  }

  .loading {
    width: 15px;
    height: 15px;
    background: url('@/assets/image/loading.svg') no-repeat center;
    margin-right: 12px;
    animation: loading 2s linear infinite;
  }

  .loading-active {
    background: rgba(52, 94, 255, 0.30);
  }
}

@keyframes loading {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
